import React from 'react'
import Link from 'next/link'
import 'styles/addArticle/addArticle.scss'
import Ueditor from '../../layout/Ueditor'
import Uploadimg from './uploadimg'
import fetchData from '/utils/fetchData'
import Router from 'next/router'
import PopModal from '../../layout/PopModal'
import { Form, Icon, Input, Button, Cascader,message,Modal } from 'antd';

const options = [{
    type: '1',
    vaule: 'Zhejiang',
    threeList: [{
        type: '2',
      vaule: 'Hangzhou',
      threeList: [{
        type: '3',
        vaule: 'West Lake',
      }],
    }],
  }, {
    type: '4',
    vaule: 'Jiangsu',
    threeList: [{
        type: '5',
      vaule: 'Nanjing',
    }],
  }];
  
class Content extends React.Component{
    constructor(props) {
        super(props)
        this.state={
            imageflag:false,
            coverImgUrl:"",
            titleInput:"",//标题输入框
            typeList:[],
            twoStageType:"",//二级
            threeLevelType:"",//三级
            detail:"",//文章内容
            contentId:"",
            isSend:true,//草稿发送状态
            popShow:false,//遮罩显示状态
        }
    }

    componentWillUnmount(){//在组件从 DOM 中移除的时候立刻被调用。
        UE.getEditor('content').execCommand( 'clearlocaldata' );
        if(this.state.isSend){
            this.saveCg();
        }
    }
    componentDidMount(){
        if(!JSON.parse(sessionStorage.getItem('user'))){
            Router.push({
                pathname: '/index',
            })
        }
        this.setState({//打开遮罩
            popShow:true,
        });
        setTimeout(() => {
            this.setState({//关闭遮罩
                popShow:false,
            });
        }, 1000);
        // var id = window.location.href.split('=')[1]?window.location.href.split('=')[1]:''
        var id = this.props.contentId ? this.props.contentId : ''
        console.log(id)        
        this.setState({
            contentId:id,
        },()=>{
            if(this.state.contentId){
                console.log("编辑数据");
                fetchData.get('/content/pc/content/query/by/id?contentId='+this.state.contentId,{headers:{"Authorization":"bearer "+JSON.parse(sessionStorage.getItem('user')).access_token+""}})
                .then((response)=>{
                    // console.log(UE.plugin.register());
                    this.setState({
                        coverImgUrl:response.respData.imageAddr,
                        titleInput:response.respData.title,//标题输入框
                        twoStageType:response.respData.typeId,
                        threeLevelType:response.respData.threeType,
                        detail:response.respData.detail,//文章内容
                    })
                })
                .catch((error)=> {
                });
            }else{
                console.log("新增文章");
            }
        })
        
        fetchData.get('/system/masterData/pc/three/list/query?type=5',{headers:{"Authorization":"bearer "+JSON.parse(sessionStorage.getItem('user')).access_token+""}})
        .then((response)=>{
            this.setState({
                typeList:response.respData.resultData
            })
        })
        .catch((error)=> {
        });
    }
    onChange(value) {
        this.setState({
            twoStageType:value[0]?value[0]:'',
            threeLevelType:value[1]?value[1]:''
        })
    }
    imageuploaded() {
        this.setState({
            imageflag:true
        });
    }
    closeFn(){
        this.setState({
            imageflag:false
        });
    }
    urlFn(url){
        this.setState({
            imageflag:false,
            coverImgUrl:url
        });
    }
    inputChange(event){
        this.setState({
            titleInput:event.target.value
        })
    }
    saveCg(){//lowbee写法 保存草稿
        if(!this.state.titleInput && !this.state.twoStageType && !this.state.coverImgUrl && UE.getEditor('content').getContent().length == 0){
            console.log("四项未填，不存数据");
            return
        }
        var data = {
            title:this.state.titleInput,//文章标题
            typeId:this.state.twoStageType,//文章类型
            threeType:this.state.threeLevelType,
            imageAddr:this.state.coverImgUrl,//文章封面            
            detail:UE.getEditor('content').getContent(),           
            id:this.state.contentId ? this.state.contentId:''
        }
        var data2 = {
            title:this.state.titleInput,//文章标题
            typeId:this.state.twoStageType,//文章类型
            threeType:this.state.threeLevelType,
            imageAddr:this.state.coverImgUrl,//文章封面            
            detail:UE.getEditor('content').getContent(),           
        }
        if(this.state.contentId){
            fetchData.post('/content/pc/content/update',data,{headers:{"Authorization":"bearer "+JSON.parse(sessionStorage.getItem('user')).access_token+""}})
            .then((response)=>{
                UE.getEditor('content').execCommand( 'clearlocaldata' );
                Router.push({
                    pathname: '/draftBox',
                })
                
            })
            .catch((error)=> {
            });
        }else{
            fetchData.post('/content/pc/content/add',data2,{headers:{"Authorization":"bearer "+JSON.parse(sessionStorage.getItem('user')).access_token+""}})
            .then((response)=>{
                UE.getEditor('content').execCommand( 'clearlocaldata' );
                Router.push({
                    pathname: '/draftBox',
                })
                
            })
            .catch((error)=> {
            });
        } 
    }
    saveFun(type){
        //保存草稿箱
        if(type == 2){
            if(this.state.titleInput =="" || this.state.titleInput.length == 0 ){
                message.error('请输入文章标题');
                return;
            }
            if(this.state.threeLevelType == "" && this.state.twoStageType == "" ){
                message.error('请选择文章类型');
                return;
            }
            if(this.state.coverImgUrl ==""){
                message.error('请上传封面图片');
                return;
            }
            if(UE.getEditor('content').getContent() =="" || UE.getEditor('content').getContent().length == 0 ){
                message.error('请输入文章内容');
                return;
            }
        }
        var data = {
            title:this.state.titleInput,//文章标题
            typeId:this.state.twoStageType,//文章类型
            threeType:this.state.threeLevelType,
            imageAddr:this.state.coverImgUrl,//文章封面            
            detail:UE.getEditor('content').getContent(),           
            id:this.state.contentId ? this.state.contentId:''
        }
        var data2 = {
            title:this.state.titleInput,//文章标题
            typeId:this.state.twoStageType,//文章类型
            threeType:this.state.threeLevelType,
            imageAddr:this.state.coverImgUrl,//文章封面            
            detail:UE.getEditor('content').getContent(),           
        }
        Modal.confirm({
            content:"确定要执行该操作吗？",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                if(type == 1){
                    this.setState({
                        isSend:false,
                    },()=>{
                        this.saveCg();
                    })
                }else{
                    this.setState({
                        isSend:false,
                    },()=>{
                        fetchData.post('/content/pc/content/submit/audit',data,{headers:{"Authorization":"bearer "+JSON.parse(sessionStorage.getItem('user')).access_token+""}})
                        .then((response)=>{
                            UE.getEditor('content').execCommand( 'clearlocaldata' );
                            Router.push({
                                pathname: '/myArticle',
                            })
                        })
                        .catch((error)=> {
                        });
                    })
                    
                }
            },
            onCancel:()=>{}
        })         
    }
    render(){
        return (
            <div className="AddArticleContent">
                <PopModal popShow={this.state.popShow}/>
                <div className="top">
                    <div className="tip">
                        <span className="label">标题</span>
                        <div className="con" style={{width:'690px'}}>
                            <Input placeholder="请输入标题（限20字以内）" maxLength="20" value={this.state.titleInput} onChange={this.inputChange.bind(this)}/>
                        </div>
                    </div>
                    <div className="tip">
                        <span className="label">类型</span>
                        <div className="con" style={{width:'326px'}}>
                            {
                                this.state.contentId ?
                                <Cascader  options={this.state.typeList} value={[this.state.twoStageType,this.state.threeLevelType]} onChange={this.onChange.bind(this)} placeholder="请选择类型" />
                                :
                                <Cascader  options={this.state.typeList}  onChange={this.onChange.bind(this)} placeholder="请选择类型" />                               
                            }
                        </div>
                    </div>
                    <div className="tip">
                        <span className="label">封面</span>
                        <div className="con">
                            <img className="coverImg" src={this.state.coverImgUrl ? this.state.coverImgUrl : '/static/addarticle/upload_img.png' } alt=""/>
                            <div className="chooseImg">
                                <div onClick={this.imageuploaded.bind(this)} className="updateimgbtn">选择文件</div>
                                <p>建议宽度600*400像素</p>
                            </div>                           
                        </div>
                    </div>
                </div>
                {
                    this.state.imageflag?
                    <Uploadimg width={602} height={402} visible={this.state.imageflag} closeModal={this.closeFn.bind(this)} urlFn={this.urlFn.bind(this)}/>
                    :''
                }
                <Ueditor  id="content" value={this.state.detail} height="300" />
                <div className="btnWrap">
                    <div className="saveBtn" onClick={this.saveFun.bind(this,1)}><div className="hoverBtn"></div>保存草稿</div>
                    <div className="sendBtn" onClick={this.saveFun.bind(this,2)}><div className="hoverBtn"></div>提交审核</div>
                </div>               
            </div>
            
        )
    }

}
export default Content